<template>
	<view class="container flex-c">
		<uni-nav-bar class="ch-nav" height="88rpx" backgroundColor="#ffffff" leftWidth="90rpx" rightWidth="90rpx" color="#333" :fixed="true" :padding="false" :border="true" @clickLeft="$goBack(1)" @clickRight="submit">
			<template slot="left">
				<image class="left" src="@/public/images/public/dhl_fhjt.png" mode="aspectFit"></image>
			</template>
			<text class="title">发布讨论帖</text>
			<template slot="right">
				<text class="text-primary" :class="complete ? 'color-blue' : 'color-grey'">发布</text>
			</template>
		</uni-nav-bar>
		<view class="head flex-r ac text-secondary">
			<view class="tab flex-r ac jc color-grey" v-for="(item, index) in discussType" :key="index" :class="item.type+' '+(active == index ? 'active' : '')" @tap="tabChange(index)">
				<text>{{item.title}}</text>
			</view>
		</view>
		<view class="body">
			<ContentEditor 
				:class="discussType[active].type" 
				:type="discussType[active].type" 
				:placeholder="'请输入'+discussType[active].title+'内容...'" 
				:height="editorHeight" 
				@change="contentChange"
			>
				<template slot="header">
					<view class="discuss-title flex-r ac">
						<textarea
							class="textarea" 
							v-model="article.title" 
							:minlength="10" 
							:maxlength="30" 
							:auto-height="true" 
							@blur="inputBlur"
							@input="inputTitle"
							:placeholder="'请输入'+discussType[active].title+'标题（最多30个字）'">
						</textarea>
						<!-- <input class="input" v-model="article.title" :placeholder="'请输入'+discussType[active].title+'标题（最多30个字）'" :minlength="10" :maxlength="30" @blur="inputBlur" @input="inputTitle" /> -->
					</view>
				</template>
				<template slot="footer">
					<view class="vote-box" v-show="active == 1">
						<text class="vote-title text-large flex-r ac">投票选项</text>
						<scroll-view class="scroll-Y" :scroll-y="true" :scroll-into-view="scrollView" :scroll-with-animation="true">
							<view class="vote-body" v-if="article.discussOptionList">
								<view class="vote-item flex-r ac jc" v-for="(item, index) in article.discussOptionList" :key="index" :id="'item_'+index">
									<input class="item-input" type="text" v-model="article.discussOptionList[index].title" placeholder="请输入选项名称" :maxlength="10" @input="voteInput" />
									<image class="delete-icon" src="@/public/images/bar/scxx.png" mode="widthFix" v-if="index > 1" @tap="removeVoteItem(index)"></image>
								</view>
								<button type="default" class="addbtn flex-r ac jc" @touchend.prevent="addVoteItem" @tap="addVoteItem">
									<image class="add-icon" src="@/public/images/bar/xz.png" mode="widthFix"></image>
									<text class="text-regular color-blue">新增选项</text>
								</button>
							</view>
						</scroll-view>
					</view>
				</template>
			</ContentEditor>
		</view>
	</view>
</template>

<script>
	import * as qiniu from 'qiniu-js'
	import ContentEditor from '../components/ch-editor/ch-contenteditor.vue'
	export default {
		data() {
			return {
				discussType: [
					{title: '话题帖', type: 'topic', value: 6}, 
					{title: '投票帖', type: 'vote', value: 7}
				],
				active: 0,
				article: {
					forumId: null,
					type: 6,
					title: null,
					content: null,
					imageUrl: null,
					discussOptionList: null
				},
				imageUrlList: [],
				scrollView: '',
				lineCount: 0,
			};
		},
		components: {
			ContentEditor
		},
		computed: {
			complete() {
				let status = this.article.title && this.article.title.length >= 10
				if(this.active == 0){
					let len = this.$CHS.checkTextLength(this.article.content)
					return status && this.article.content && len >= 50
				}else{
					let num = 0
					for(let item of this.article.discussOptionList){
						if(item.title){
							num++
						}
					}
					return status && this.article.discussOptionList && num >= 2
				}
			},
			editorHeight() {
				if(this.active == 0){
					return 'calc(var(--safe-height) - var(--navbar-height) - 88rpx - 96rpx - 120rpx)';
				}else{
					return 'calc(var(--safe-height) - var(--navbar-height) - 88rpx - 120rpx - 550rpx - 96rpx)';
				}
			}
		},
		onLoad() {
			console.log(this.$Route.query);
			if(this.$Route.query.bid){
				this.article.forumId = this.$Route.query.bid
			}else{
				//非法请求处理
				uni.showToast({
					title: '请求数据错误，请返回重试',
					icon: 'none'
				})
				this.$goBack(1)
			}
		},
		methods: {
			submit() {
				if(this.complete){
					if(this.active == 0){
						this.$set(this.article, 'discussOptionList', null)
					}else{
						let tempOptionList = []
						let num = 1
						for(let item of this.article.discussOptionList){
							if(item.title){
								if(!tempOptionList.includes(item.title)){
									tempOptionList.push({title: item.title, sort: num})
									num++
								}else{
									tempOptionList = []
									break
								}
							}
						}
						if(tempOptionList.length == 0){
							uni.showToast({
								title: '选项名称不能重复',
								icon: 'none'
							})
							return false
						}else{
							console.log(tempOptionList);
							this.article.discussOptionList = tempOptionList
						}
					}
					this.$CHS.getQiniuToken().then(async (result)=>{
						this.token = result.token
						this.imageDomain = result.url
						//开始上传图片
						this.$ShowLoading({show: true})
						if(this.article.content){
							let content = await this.relpaceUrlImage(this.article.content, 'vip')
							if(content){
								this.article.content = content
								this.article.imageUrl = this.imageUrlList.toString()
							}else{
								return
							}
						}
						//上传结束
						this.$ShowLoading({show: false})
						this.$http.post({
							url: '/api/dynamic/add',
							data: this.article
						}).then((data) => {
							console.log(data);
							if(data.success){
								//成功提示
								this.$ShowToast({text: '发布成功'})
								uni.showToast({
									title: '发布成功',
									icon: 'success'
								})
								this.reload(this.article.forumId)
							}else{
								uni.showToast({
									title: data.message || '发布失败',
									icon: 'none'
								})
							}
						}).catch((err) => {
							console.log(err);
							uni.showToast({
								title: '发布失败，请稍后重试',
								icon: 'none'
							})
						})
					}).catch((err) => {
						console.log(err);
						uni.showToast({
							title: '网络异常，请重试',
							icon: 'none'
						})
					})
				}else{
					if(this.article.title && this.article.title.length < 10){
						uni.showToast({
							title: '标题不少于10个字',
							icon: 'none'
						})
						return
					}
					if(this.active == 0){
						let len = this.$CHS.checkTextLength(this.article.content)
						if(len < 50){
							uni.showToast({
								title: '内容长度不少于50字，当前字数：' + len,
								icon: 'none'
							})
							return false
						}
						uni.showToast({
							title: '请填写标题和内容',
							icon: 'none'
						})
					}else{
						uni.showToast({
							title: '请填写标题和投票选项',
							icon: 'none'
						})
					}
				}
			},
			//发布成功后刷新页面
			reload(barId) {
				let pages = getCurrentPages()
				let len = pages.length
				if(len > 1){
					console.log(pages);
					let page = pages[len - 2]
					if(page && page.refreshList){
						setTimeout(()=>{
							page.refreshList(0)
						}, 1000)
					}
					setTimeout(() => {
						this.$goBack(1);
					}, 500)
				}else{
					setTimeout(() => {
						this.$Router.replaceAll({name: 'barhome', params: {bid: barId}})
					}, 500)
				}
			},
			tabChange(index){
				this.active = index
				this.article.type = this.discussType[index].value
				if(this.active == 1 && !this.article.discussOptionList){
					this.$set(this.article, 'discussOptionList', [{title: '', sort: 1},{title: '', sort: 2}])
				}
			},
			contentChange(e) {
				this.article.content = e.html
			},
			//标题输入换行
			lineChange(e){
				console.log(e);
				this.lineCount = e.detail.lineCount
			},
			//检测字数
			inputBlur(e) {
				if(e.detail.value) {
					if(e.detail.value.length < 10){
						uni.showToast({
							title: '标题不少于10个字',
							icon: 'none'
						})
					}
				}
			},
			//检测输入字数
			inputTitle(e) {
				if(e.detail.value) {
					if(e.detail.value.length >= 30){
						uni.showToast({
							title: '标题最多30个字',
							icon: 'none'
						})
					}
				}
			},
			addVoteItem() {
				this.article.discussOptionList.push({title: '', sort: this.article.discussOptionList.length + 1})
				setTimeout(()=>{
					this.scrollView = 'item_' + (this.article.discussOptionList.length - 1)
					this.$nextTick(()=>{
						this.scrollView = ''
					})
				}, 50)
			},
			removeVoteItem(index) {
				this.article.discussOptionList.splice(index, 1)
			},
			voteInput(e){
				if(e.detail.value && e.detail.value.length >= 10){
					uni.showToast({
						title: '选项最多输入10个字',
						icon: 'none'
					})
				}
			},
			//富文本图片上传替换
			relpaceUrlImage(html, flag) {
				return new Promise((resolve,reject)=>{
					let imgReg = /<img.*?(?:>|\/>)/gi;
					let imgList = html.match(imgReg);
					if (imgList != null) {
						this.imageUrlList = []
						let len = imgList.length
						let rpNum = 0
						imgList.forEach( async (item) => {
							let srcReg = /src=['"]?([^'"]*)['"]?/i
							var src = item.match(srcReg)
							var url = src[1]
							if(url.indexOf(this.imageDomain) > -1){
								rpNum += 1
								this.imageUrlList.push(url)
								if(rpNum == len){
									resolve(html);
								}
							}else{
								let name = Date.now() + '.png'
								let type = 'image/png'
								try{
									await this.convertImgToBlob(url, (blob)=>{
										let file = new window.File([blob], name, { type: type })
										this.qiniuUploadImage(file).then((res)=>{
											let newSrc = this.imageDomain + '/' + res.key
											html = html.replace(src[1], newSrc)
											if(flag == 'free'){
												this.article.freeContent = html
											}else if(flag == 'vip'){
												this.article.content = html
											}else if(flag == 'video'){
												this.article.freeContent = html
											}
											console.log(html);
											rpNum += 1
											this.imageUrlList.push(newSrc)
											if(rpNum == len){
												resolve(html);
											}
										}).catch((res)=>{
											console.log(res);
											reject(false);
											this.$ShowLoading({show: false})
											uni.showToast({
												title: '图片上传失败，请检查网络并重试',
												icon: 'none'
											})
											throw new Error('upload error');
										})
									}, (url)=>{
										console.log(url);
										reject(false);
										this.$ShowLoading({show: false})
										uni.showToast({
											title: '图片上传错误，请检查网络并重试',
											icon: 'none'
										})
										throw new Error('upload error');
									})
								}catch(e){
									console.log(e);
									reject(false);
									this.$ShowLoading({show: false})
									uni.showToast({
										title: '图片上传异常，请检查网络并重试',
										icon: 'none'
									})
								}
							}
						})
					}else{
						resolve(html);
					}
				})
			},
			//图片Blob转换
			convertImgToBlob(url, callback, error) {
				const img = new Image()
				img.crossOrigin = 'Anonymous' 
				img.onload = function () {
					let canvas = document.createElement('canvas')
					const ctx = canvas.getContext('2d')
					canvas.height = this.height
					canvas.width = this.width
					ctx.drawImage(this, 0, 0)
					canvas.toBlob(callback)
					canvas = null
				}
				img.onerror = function() {
					error(url)
				}
				img.src = url
			},
			//七牛上传图片
			qiniuUploadImage(file) {
				return new Promise((resolve,reject)=>{
					let type = file.type.substr(6)
					let randomStr = this.$CHS.randomString(10)
					let key = Date.now() + randomStr + 'H5.' + type
					const observer = {
						next(res){
							console.log(res);
						},
						error(err){
							console.log(err);
							reject(err)
						},
						complete(res){
							console.log(res);
							resolve(res)
						}
					}
					const options = {
						quality: 0.4,
						noCompressIfLarger: true
					}
					//压缩图片
					qiniu.compressImage(file, options).then(data => {
						const observable = qiniu.upload(data.dist, key, this.token)
						const subscription = observable.subscribe(observer) // 上传开始
					})
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		.ch-nav{
			.text-primary{
				margin-right: 20rpx;
			}
		}
	}
	.head{
		width: 100%;
		height: 88rpx;
		background: #F2F5FA;
		box-sizing: border-box;
		padding: 0 20rpx;
		.tab{
			width: 200rpx;
			height: 60rpx;
			border-radius: 30rpx;
			background-size: 100%;
			background-position: center;
			background-repeat: no-repeat;
			margin-right: 30rpx;
			&.topic{
				background-image: url('@/public/images/bar/httbg_wxz.png');
			}
			&.vote{
				background-image: url('@/public/images/bar/tptbg_wxz.png');
			}
			&.active{
				color: #0055FF;
				&.topic{
					background-image: url('@/public/images/bar/httbg_xz.png');
				}
				&.vote{
					background-image: url('@/public/images/bar/tptbg_xz.png');
				}
			}
		}
	}
	.body{
		height: calc(var(--safe-height) - #{$navbar-height} - 88rpx - 96rpx);
		background-color: #ffffff;
		.content-editor{
			.discuss-title{
				margin: 0 20rpx;
				height: 120rpx;
				border-bottom: 1rpx solid #ededed;
				box-sizing: border-box;
				/deep/ .textarea{
					width: 100%;
					font-size: 36rpx;
					font-weight: 500;
					line-height: 1.25;
					box-sizing: border-box;
					.textarea-placeholder{
						font-size: 36rpx;
						font-weight: 500;
						color: #B3B3B3;
					}
				}
			}
			.vote-box{
				margin: 0 20rpx;
				border-top: 1rpx solid #ededed;
				box-sizing: border-box;
				height: calc(550rpx + 96rpx + var(--safe-area-inset-bottom));
				.vote-title{
					line-height: 96rpx;
					font-weight: 500;
				}
				.scroll-Y{
					height: calc(454rpx + 96rpx + var(--safe-area-inset-bottom));
				}
				.vote-body{
					padding-bottom: calc(40rpx + 96rpx + var(--safe-area-inset-bottom));
					.vote-item{
						position: relative;
						height: 88rpx;
						background: #F2F5FA;
						border: 1rpx solid #CCCCCC;
						border-radius: 10rpx;
						margin-bottom: 20rpx;
						box-sizing: border-box;
						.item-input{
							width: calc(100% - 120rpx);
							text-align: center;
							/deep/ .input-placeholder{
								font-size: 28rpx;
								color: #B3B3B3;
								line-height: 52rpx;
							}
						}
						.delete-icon{
							position: absolute;
							right: 20rpx;
							width: 32rpx;
						}
					}
					.addbtn{
						height: 88rpx;
						background: #FFFFFF;
						border: 2rpx dashed #4D88FF;
						border-radius: 10rpx;
						box-sizing: border-box;
						.add-icon{
							margin-right: 9rpx;
							width: 32rpx;
						}
					}
				}
				.vote-body::-webkit-scrollbar{
					display: none;
				}
			}
		}
	}
</style>
